package com.nhjf.mobile.controller.artPictures;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.nhjf.command.comment.CreateCoursesCommentCommand;
import com.nhjf.common.page.Pagination;
import com.nhjf.mobile.common.util.ImageTools;
import com.nhjf.mobile.common.util.SysProperties;
import com.nhjf.mobile.controller.BaseController;
import com.nhjf.model.cn_nojd.Cnnojd;
import com.nhjf.model.student.Student;
import com.nhjf.model.system.AdminSession;
import com.nhjf.model.system.User;
import com.nhjf.model.teachers.ArtPictures;
import com.nhjf.model.teachers.ArtPicturesCollection;
import com.nhjf.model.teachers.ArtPicturesComment;
import com.nhjf.model.teachers.Courses;
import com.nhjf.model.teachers.CoursesComment;
import com.nhjf.model.teachers.ReviewPaintingCollection;
import com.nhjf.model.teachers.Teacher;
import com.nhjf.pojo.dto.result.ServiceResultDto;
import com.nhjf.pojo.qo.studnet.StudentQo;
import com.nhjf.pojo.qo.system.AdminSessionQo;
import com.nhjf.pojo.qo.system.UserQo;
import com.nhjf.pojo.qo.teachers.ArtPicturesCollectionQo;
import com.nhjf.pojo.qo.teachers.ArtPicturesCommentQo;
import com.nhjf.pojo.qo.teachers.ArtPicturesQo;
import com.nhjf.pojo.qo.teachers.CoursesCommentQo;
import com.nhjf.pojo.qo.teachers.CoursesQo;
import com.nhjf.pojo.qo.teachers.ReviewPaintingCollectionQo;
import com.nhjf.pojo.qo.teachers.TeachersQo;
import com.nhjf.service.cn_nojd.CnnojdService;
import com.nhjf.service.student.StudentService;
import com.nhjf.service.system.AdminSessionService;
import com.nhjf.service.system.UserService;
import com.nhjf.service.teachers.ArtPicturesCollectionService;
import com.nhjf.service.teachers.ArtPicturesCommentService;
import com.nhjf.service.teachers.ArtPicturesService;
import com.nhjf.service.teachers.TeachersService;

import net.sf.json.JSONObject;

/**
 * @类功能说明：作品管理
 * @部门：技术部
 * @作者：龚一凡
 * @版本：V1.0
 */
@Controller
@RequestMapping(value = "/artPictures")
public class ArtPicturesController extends BaseController{

	@Autowired
	private ArtPicturesService artPicturesService;
	@Autowired
	private ArtPicturesCommentService artPicturesCommentService;
	@Autowired
	private AdminSessionService adminSessionService;
	@Autowired
	private UserService userService;
	@Autowired
	private TeachersService teachersService;
	@Autowired
	private StudentService studentService;
	@Autowired
	private CnnojdService cnnojdService;
	@Autowired
	private ArtPicturesCollectionService artPicturesCollectionService;
	/**
	 * 
	 * @方法功能说明：作品列表
	 * @修改者名字：龚一凡
	 * @修改内容：
	 * @参数：
	 * @return:
	 * @throws
	 */
	@ResponseBody
	@RequestMapping(value = "/queryArtPictures")
	public String queryArtPictures(HttpServletRequest request, Model model, @RequestParam(value="userId", required=true) String userId,@RequestParam(value="page", defaultValue="1")Integer page){

		Map<String, Object> resMap=new HashMap<String, Object>();
		Pagination pagination = new Pagination();
		pagination.setPageSize(10);
		ArtPicturesQo artPicturesQo=new ArtPicturesQo();
		artPicturesQo.setUserId(Long.parseLong(userId));
		pagination.setCondition(artPicturesQo);
		pagination.setPageNo(page);
		pagination = artPicturesService.queryPagination(pagination);
		List<ArtPictures> list=(List<ArtPictures>)pagination.getList();
		SimpleDateFormat format1=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		SysProperties sysProperties=SysProperties.getInstance();
		String imagePath=sysProperties.get("commentImagePath");
		for(ArtPictures artPictures:list) {
			if(artPictures.getUser()!=null) {
				artPictures.getUser().setUserPassword("");
			}
			String fom= format1.format(artPictures.getCreatTime());
			artPictures.setCreatdate(fom);
			artPictures.setArtPicturesUrl(artPictures.getArtPicturesUrl()==null?"":imagePath+"/artPictures/"+artPictures.getArtPicturesUrl());
		}


		resMap.put("code", "200");
		resMap.put("message", pagination);
		return JSONObject.fromObject(resMap).toString();
	}
	
	
	/**
	 * 
	 * @方法功能说明：作品列表
	 * @修改者名字：龚一凡
	 * @修改内容：
	 * @参数：
	 * @return:
	 * @throws
	 */
	@ResponseBody
	@RequestMapping(value = "/queryStudentArtPictures")
	public String queryStudentArtPictures(HttpServletRequest request, Model model, @RequestParam(value="studentId", required=true) String studentId,@RequestParam(value="page", defaultValue="1")Integer page){

		Map<String, Object> resMap=new HashMap<String, Object>();
		StudentQo studentQo=new StudentQo();
		studentQo.setSeachStudent(true);
		studentQo.setStudentId(Long.parseLong(studentId));
		Student student=studentService.queryUnique(studentQo);
		Pagination pagination = new Pagination();
		pagination.setPageSize(10);
		ArtPicturesQo artPicturesQo=new ArtPicturesQo();
		artPicturesQo.setUserId(student.getUser().getId());
		pagination.setCondition(artPicturesQo);
		pagination.setPageNo(page);
		pagination = artPicturesService.queryPagination(pagination);
		List<ArtPictures> list=(List<ArtPictures>)pagination.getList();
		SimpleDateFormat format1=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		SysProperties sysProperties=SysProperties.getInstance();
		String imagePath=sysProperties.get("commentImagePath");
		for(ArtPictures artPictures:list) {
			if(artPictures.getUser()!=null) {
				artPictures.getUser().setUserPassword("");
			}
			String fom= format1.format(artPictures.getCreatTime());
			artPictures.setCreatdate(fom);
			artPictures.setArtPicturesUrl(artPictures.getArtPicturesUrl()==null?"":imagePath+"/artPictures/"+artPictures.getArtPicturesUrl());
		}


		resMap.put("code", "200");
		resMap.put("message", pagination);
		return JSONObject.fromObject(resMap).toString();
	}
	/**
	 * 
	 * @方法功能说明：当前登陆用户作品列表
	 * @修改者名字：龚一凡
	 * @修改内容：
	 * @参数：
	 * @return:
	 * @throws
	 */
	@ResponseBody
	@RequestMapping(value = "/queryTokenArtPictures")
	public String queryTokenArtPictures(HttpServletRequest request, Model model, @RequestParam(value="token", required=true) String token,@RequestParam(value="page", defaultValue="1")Integer page){

		Map<String, Object> resMap=new HashMap<String, Object>();
		AdminSessionQo adminSessionQo=new AdminSessionQo();
		adminSessionQo.setToken(token);
		AdminSession adminSession=adminSessionService.queryUnique(adminSessionQo);
		if(adminSession==null) {
			resMap.put("code", "406");
			resMap.put("message", "不存在此账号！");
			return JSONObject.fromObject(resMap).toString();
		}else {
			UserQo userQo=new UserQo();
			userQo.setUserName(adminSession.getLoginName());
			User user= userService.queryUnique(userQo);
			if(user==null) {
				resMap.put("code", "406");
				resMap.put("message", "未登录!");
				return JSONObject.fromObject(resMap).toString();
			}else {
				Pagination pagination = new Pagination();
				pagination.setPageSize(10);
				ArtPicturesQo artPicturesQo=new ArtPicturesQo();
				artPicturesQo.setUserId(user.getId());
				pagination.setCondition(artPicturesQo);
				pagination.setPageNo(page);
				pagination = artPicturesService.queryPagination(pagination);
				List<ArtPictures> list=(List<ArtPictures>)pagination.getList();
				SimpleDateFormat format1=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
				SysProperties sysProperties=SysProperties.getInstance();
				String imagePath=sysProperties.get("commentImagePath");
				for(ArtPictures artPictures:list) {
					if(artPictures.getUser()!=null) {
						artPictures.getUser().setUserPassword("");
					}
					String fom= format1.format(artPictures.getCreatTime());
					artPictures.setCreatdate(fom);
					artPictures.setArtPicturesUrl(artPictures.getArtPicturesUrl()==null?"":imagePath+"/artPictures/"+artPictures.getArtPicturesUrl());
				}


				resMap.put("code", "200");
				resMap.put("message", pagination);
				return JSONObject.fromObject(resMap).toString();
				}
			}
	

	}
	/**
	 * 作品详情
	 * @param artPicturesId
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/artPicturesDetails")
	public String artPicturesDetails( @RequestParam(value="artPicturesId", required=true) String artPicturesId,@RequestParam(value="token", required=false)String token) {
		Map<String, Object> resMap=new HashMap<String, Object>();
		ArtPicturesQo qo=new ArtPicturesQo();
		qo.setSeachUser(true);
		qo.setArtPicturesId(Long.parseLong(artPicturesId));
		ArtPictures artPictures=artPicturesService.queryUnique(qo);
		if(artPictures!=null) {
			if(artPictures.getUser()!=null) {
				artPictures.getUser().setUserPassword("");
			}
			if(StringUtils.isNotBlank(token)) {
				AdminSessionQo adminSessionQo=new AdminSessionQo();
				adminSessionQo.setToken(token);
				AdminSession adminSession=adminSessionService.queryUnique(adminSessionQo);
				if(adminSession==null) {

				}else {
					UserQo userQo=new UserQo();
					userQo.setUserName(adminSession.getLoginName());
					User user= userService.queryUnique(userQo);
					if(user==null) {

					}else {
						ArtPicturesCollectionQo artPicturesCollectionQo=new ArtPicturesCollectionQo();
						artPicturesCollectionQo.setArtPicturesId(Long.parseLong(artPicturesId));
						artPicturesCollectionQo.setUserId(user.getId());
						ArtPicturesCollection artPicturesCollection= artPicturesCollectionService.queryUnique(artPicturesCollectionQo);
						if(artPicturesCollection!=null) {
							artPictures.setIsCollectionArt(1);
						}else {
							artPictures.setIsCollectionArt(0);
						}
					}
				}
			}
			resMap.put("code", "200");
			SysProperties sysProperties=SysProperties.getInstance();
			String imagePath=sysProperties.get("imagePath");
			artPictures.setArtPicturesUrl(imagePath+"/artPictures/"+artPictures.getArtPicturesUrl());
			resMap.put("message", artPictures);
			SimpleDateFormat format1=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			String fom= format1.format(artPictures.getCreatTime());
			artPictures.setCreatdate(fom);
			if(artPictures.getUserType()==1) {
				TeachersQo teacherQo=new TeachersQo();
				teacherQo.setUserId(artPictures.getUser().getId());
				teacherQo.setSeachUser(true);
				Teacher teacher=teachersService.queryUnique(teacherQo);
				if(teacher!=null) {
					artPictures.setIdentity(7);
					if(teacher.getUser().getProvince()!=null) {
						Cnnojd province= cnnojdService.get(teacher.getUser().getProvince());
						if(province!=null) {
							artPictures.setProvince(province.getName());
						}

					}
					artPictures.setAvatar(imagePath+"/picture/"+teacher.getAvatar());
					artPictures.setNickname(teacher.getNickname());
				}
			}else {
				StudentQo studentQo=new StudentQo();
				studentQo.setUserid(artPictures.getUser().getId());
				studentQo.setSeachStudent(true);
				Student student=studentService.queryUnique(studentQo);
				if(student!=null) {
	
					if(StringUtils.isNotEmpty(student.getIdentity())) {
						artPictures.setIdentity(Integer.parseInt(student.getIdentity()));
					}else {
						artPictures.setIdentity(0);
					}
					if(student.getUser().getProvince()!=null) {
						Cnnojd province= cnnojdService.get(student.getUser().getProvince());
						if(province!=null) {
							artPictures.setProvince(province.getName());
						}

					}
					artPictures.setAvatar(imagePath+"/picture/"+student.getAvatar());
					artPictures.setNickname(student.getNickname());
				}
			}
			return JSONObject.fromObject(resMap).toString();

		}else {
			resMap.put("code", "500");
			resMap.put("message", "作品不存在");
			return JSONObject.fromObject(resMap).toString();
		}
	}

	/**
	 * 作品新增
	 * @param file
	 * @param artName
	 * @param token
	 * @param typeOne
	 * @param typeTwo
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/artPicturesAdd")
	public String artPicturesAdd(@RequestParam("file") MultipartFile file,@RequestParam(value="artName", required=true)String artName,@RequestParam(value="token", required=true)String token,@RequestParam(value="typeOne", required=true)String typeOne,@RequestParam(value="typeTwo", required=true)String typeTwo) {
		Map<String, Object> resMap=new HashMap<String, Object>();
		AdminSessionQo adminSessionQo=new AdminSessionQo();
		adminSessionQo.setToken(token);
		AdminSession adminSession=adminSessionService.queryUnique(adminSessionQo);
		if(adminSession==null) {
			resMap.put("code", "406");
			resMap.put("message", "不存在此账号！");
			return JSONObject.fromObject(resMap).toString();
		}else {

			UserQo userQo=new UserQo();
			userQo.setUserName(adminSession.getLoginName());
			User user= userService.queryUnique(userQo);
			if(user==null) {
				resMap.put("code", "406");
				resMap.put("message", "未登录!");
				return JSONObject.fromObject(resMap).toString();
			}else {
				//获取图片原始文件名
				String originalFilename = file.getOriginalFilename();
				//文件名使用当前时间
				String date = new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date());
				// 获取上传图片的扩展名(jpg/png/...)
				String extension = FilenameUtils.getExtension(originalFilename);
				String[] regular = { "JPG", "GIF","PNG","JPEG" ,"BMP"};
				boolean flag = false;
				// 判断文件格式是否合法
				for (String str : regular) {
					if (extension.equalsIgnoreCase(str)) {
						flag = true;
					}
				}
				if (!flag) {
					resMap.put("code", "500");
					resMap.put("message", "上传图片格式不正确！");
					return JSONObject.fromObject(resMap).toString();
				}

				SysProperties sysProperties=SysProperties.getInstance();
				String imgPath=sysProperties.get("artPicturesPath");
				// 图片上传的相对路径（因为相对路径放到页面上就可以显示图片）

				String path =imgPath+user.getId()+"/" + date + "." + extension;
				//图片上传的绝对路径

				File dir = new File(path);
				if (!dir.exists()) {
					dir.mkdirs();
				}
				// 上传图片
				try {
					file.transferTo(new File(path));
					int width=ImageTools.getImgWidth(dir);
					int height=ImageTools.getImgHeight(dir);
					ServiceResultDto serviceResultDto =artPicturesService.createArtPictures(user.getId()+"/" + date + "." + extension, artName, width, height, user.getId(),Long.parseLong(typeOne),Long.parseLong(typeTwo));
					if(serviceResultDto.getSuccess()) {
						resMap.put("code", "200");
						resMap.put("message", "成功");
						return JSONObject.fromObject(resMap).toString();
					}
					resMap.put("code", "500");
					resMap.put("message", "操作失败");
					return JSONObject.fromObject(resMap).toString();
				} catch (IllegalStateException | IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
					resMap.put("code", "500");
					resMap.put("message", "操作失败");
					return JSONObject.fromObject(resMap).toString();
				}

			}
		}
	}
	
	/**
	 * 
	 * @方法功能说明：作品评论
	 * @修改者名字：龚一凡
	 * @修改内容：
	 * @参数：
	 * @return:
	 * @throws
	 */
	@ResponseBody
	@RequestMapping(value = "/queryArtPicturesComment")
	public String queryArtPicturesComment(HttpServletRequest request, Model model,@RequestParam(value="artPicturesId", required=true) String artPicturesId,@RequestParam(value="page", defaultValue="1")Integer page){

		Map<String, Object> resMap=new HashMap<String, Object>();
		Pagination pagination = new Pagination();
		pagination.setPageSize(10);
		ArtPicturesCommentQo qo=new ArtPicturesCommentQo();
		qo.setSeachUser(true);
		qo.setArtPicturesId(Long.parseLong(artPicturesId));
		pagination.setCondition(qo);
		pagination.setPageNo(page);
		pagination = artPicturesCommentService.queryPagination(pagination);
		List<ArtPicturesComment> artPicturesCommentList=(List<ArtPicturesComment>)pagination.getList();
		SysProperties sysProperties=SysProperties.getInstance();
		String imagePath=sysProperties.get("imagePath");
		for(ArtPicturesComment artPicturesComment:artPicturesCommentList) {
			if(artPicturesComment.getUser()!=null) {
				artPicturesComment.getUser().setUserPassword("");
			}
			
//			SimpleDateFormat format=new SimpleDateFormat("yyyy-MM-dd");
			SimpleDateFormat format1=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			String fom= format1.format(artPicturesComment.getCommentTime());
			artPicturesComment.setCommentDate(fom);
			if(artPicturesComment.getCommentUserType()==1) {
				TeachersQo teacherQo=new TeachersQo();
				teacherQo.setUserId(artPicturesComment.getUser().getId());
				Teacher teacher=teachersService.queryUnique(teacherQo);
				if(teacher!=null) {
					artPicturesComment.setAvatar(imagePath+"/picture/"+teacher.getAvatar());
					artPicturesComment.setNickname(teacher.getNickname());
				}
			}else {
				StudentQo studentQo=new StudentQo();
				studentQo.setUserid(artPicturesComment.getUser().getId());
				Student student=studentService.queryUnique(studentQo);
				if(student!=null) {
					artPicturesComment.setAvatar(imagePath+"/picture/"+student.getAvatar());
					artPicturesComment.setNickname(student.getNickname());
				}
			}
			
		}
		resMap.put("code", "200");
		resMap.put("message", pagination);
		return JSONObject.fromObject(resMap).toString();
	}
	/**
	 * 
	 * @方法功能说明：作品评论创建
	 * @修改者名字：龚一凡
	 * @修改内容：
	 * @参数：
	 * @return:
	 * @throws
	 */
	@ResponseBody
	@RequestMapping(value = "/createArtPicturesComment")
	public String createArtPicturesComment(@RequestParam(value="token", required=true)String  token,HttpServletRequest request, Model model,@RequestParam(value="artPicturesId", required=true)String artPicturesId,@RequestParam(value="comment", required=true)String comment){

		Map<String, Object> resMap=new HashMap<String, Object>();

		if(StringUtils.isEmpty(token)) {
			resMap.put("code", "500");
			resMap.put("message", "未登录!");
			return JSONObject.fromObject(resMap).toString();
		}
		AdminSessionQo adminSessionQo=new AdminSessionQo();
		adminSessionQo.setToken(token);
		AdminSession adminSession=adminSessionService.queryUnique(adminSessionQo);
		if(adminSession==null) {
			resMap.put("code", "406");
			resMap.put("message", "不存在此账号！");
			return JSONObject.fromObject(resMap).toString();
		}else {
			adminSession.getLoginName();
			UserQo userQo=new UserQo();
			userQo.setUserName(adminSession.getLoginName());
			User user= userService.queryUnique(userQo);
			if(user==null) {

				resMap.put("code", "406");
				resMap.put("message", "未登录!");
				return JSONObject.fromObject(resMap).toString();
			}else {
				
				if(StringUtils.isEmpty(comment)) {
					resMap.put("code", "500");
					resMap.put("message", "评论不能为空");
					return JSONObject.fromObject(resMap).toString();
				}
				if(StringUtils.isEmpty(artPicturesId)) {
					resMap.put("code", "500");
					resMap.put("message", "评论作品不能为空");
					return JSONObject.fromObject(resMap).toString();
				}
				ArtPictures artPictures=artPicturesService.get(Long.parseLong(artPicturesId));
				if(artPictures==null) {
					resMap.put("code", "500");
					resMap.put("message", "不存在此作品");
					return JSONObject.fromObject(resMap).toString();
				}
				ArtPicturesComment artPicturesComment=new ArtPicturesComment();
				artPicturesComment.setArtPictures(artPictures);
				artPicturesComment.setComment(comment);
				artPicturesComment.setCommentTime(new Date());
				artPicturesComment.setUser(user);
				artPicturesComment.setCommentType(1);
				TeachersQo teachersQo=new TeachersQo();
				teachersQo.setUserId(user.getId());
				Teacher teacher= teachersService.queryUnique(teachersQo);
				if(teacher==null) {
					artPicturesComment.setCommentUserType(2);
				}else {
					artPicturesComment.setCommentUserType(1);
				}
				artPicturesCommentService.save(artPicturesComment);
					resMap.put("code", "200");
					resMap.put("message", "评论成功");
					return JSONObject.fromObject(resMap).toString();


			}
		}

	}
}
